<?php
class Administrator_LoginController extends QSource_System_Controller_Action{
	public function init(){
		$this->loadTemplate('login');
	}
	public function indexAction(){ 
		$this->view->headTitle('Đăng Nhập',true);
	    if ($this->_request->isPost()) {
	        if ($this->_request->getParam('username')&&$this->_request->getParam('password')){
	        	$rememberme = $this->_request->getParam('remember-me','');
		        $auth = Zend_Auth::getInstance ();
		        $authAdapter = new Zend_Auth_Adapter_DbTable();
		        //Get prefix
	        	 $config = new Zend_Config_Ini(APPLICATION_PATH . '/configs/application.ini', APPLICATION_ENV);
				 $prefix = $config->resources->db->table_pfx;
				//End
		        $authAdapter->setTableName($prefix.'_webmaster')
		                	->setIdentityColumn('email')
		                	->setCredentialColumn('password');
		                
		        $uname = $this->_request->getParam('username');		        
		        $paswd = $this->_request->getParam('password');
		        $authAdapter->setIdentity($uname);
		        //get hash của id bởi email
		        $model = new Model_Webmaster_Webmaster();
		        $hash = $model->getHashByEmail($uname);
		        //Set credential bởi pass.'-'.hash
		        $authAdapter->setCredential(md5($paswd.'-'.$hash));
		        $select = $authAdapter->getDbSelect();
		        $select->where('status = 1');
		        $result = $auth->authenticate($authAdapter);
		        $flag = false;
		        if ($result->isValid()) {			
		            $data = $authAdapter->getResultRowObject(null, array('password'));
		            $auth->getStorage()->write($data);	
					if($rememberme==1)
					{
						$seconds  = 60 * 60 * 24 * 7;
						Zend_Session::RememberMe($seconds);
					}
					else
					{
						Zend_Session::ForgetMe();
					}
		            $flag = true;
		        }
		        if ($flag == true) {
    				$infoUser = $auth->getIdentity();
		        	$this->_redirect('/administrator');
		        }
		        else
		        {
		        	$this->view->error = "Tên đăng nhập hoặc mật khẩu không đúng.";
		        }
	        }
	        else{
	        	$this->_redirect('/administrator/login');}
	    }
	}	
	public function logoutAction() {
    	$this->_helper->viewRenderer->setNoRender();
    	$this->_helper->layout->disableLayout();
	    $auth = Zend_Auth::getInstance();
	    $auth->clearIdentity();
	    $this->_redirect('/administrator/login');
	}
}